#include"SeqList.h"
void SeqListPrint(SL* ps)
{
    int i=0;
	for ( i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}
void SeqListInit(SL* ps)  //顺序表的初始化
{
	ps->a = NULL;
	ps->size = ps->capacity = 0;
}
void SeqListDestory(SL* ps)  //销毁顺序表
{
	free(ps->a);
	ps->a = NULL;
	ps->size = ps->capacity = 0;
}

void SeqListCheckCapacity(SL* ps)  //扩容
{
	//如果空间不足或者没有空间时，就扩容
	if (ps->size == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SLDataType* tmp = (SLDataType*)realloc(ps->a, newcapacity * sizeof(SLDataType));
		if (tmp == NULL)
		{
			printf(" SeqListPushBack realloc fall !\n");
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity = newcapacity;
	}
}

void SeqListPushBack(SL* ps, SLDataType x) //尾插
{
	//如果空间不足或者没有空间时，就扩容
	/*SeqListCheckCapacity(ps);  //扩容

	//表示空间足够时直接在后面加数据
	ps->a[ps->size] = x;  
	ps->size++;
	*/
	//使用插入函数包含尾插
	SeqListInsert(ps, ps->size, x);
}
void SeqListPopBack(SL* ps)                //尾删
{
	/*assert(ps->size);
	ps->size--;*/

	/*if (ps->size > 0)
	{
		ps->size--;
	}*/
	SeqListErase(ps, ps->size-1);  //删除指定下标位置
}
void SeqListPushFront(SL* ps, SLDataType x)  //头插
{
	//如果空间不足或者没有空间时，就扩容
	/*
	SeqListCheckCapacity(ps);  //扩容

	//从尾部开始挪动数据位置
	int end = ps->size - 1;
	while (end >= 0)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[0] = x;
	ps->size++;
	*/
	SeqListInsert(ps, 0, x);
}
void SeqListPopFront(SL* ps)               //头删
{
	//判断是否有数据
	/*
	assert(ps->size > 0);
	int begin = 1;
	while (begin < ps->size)
	{
		ps->a[begin - 1] = ps->a[begin];
		begin++;
	}
	ps->size--;
	*/
	SeqListErase(ps, 0);  //删除指定下标位置

	/*
	int begin = 0;
	while (begin < ps->size - 1)
	{
		ps->a[begin] = ps->a[begin + 1];
		begin++;
	}
	ps->size--;
	*/
	
}


int SeqListFind(SL* ps, SLDataType x)   //查找位置 
{
	assert(ps->size > 0);
	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
		{
			return i;
		}
	}
	return -1;
}



void SeqListInsert(SL* ps, int pos, SLDataType x)  //指定下标位置插入
{
	//插入数据要考虑顺序表数据存储是连续的
	if (pos > ps->size || pos < 0)
	{
		printf("pos invalid!\n");
		return;
	}
	//assert(pos < =ps->size && pos >= 0);
	SeqListCheckCapacity(ps);  //增容
	//挪动数据
	int end = ps->size - 1;
	while (end >= pos)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[pos] = x;
	ps->size++;
}
void SeqListErase(SL* ps, int pos)  //删除指定下标位置
{
	assert(pos < ps->size && pos >= 0);
	int begin = pos + 1;
	while (begin < ps->size)
	{
		ps->a[begin - 1] = ps->a[begin];
		begin++;
	}
	ps->size--;

}
